self.addEventListener("message", async function (e) {
    let unLockModels = e.data;
    let maxLength = unLockModels.length;
    let components = unLockModels.map(model => model.list).flat();

    let points = components.map((com, index) => {
        com.w = 0.2;
        com.h = 0.4;
        com.x /= 1;
        com.y /= 1;
        com.rotate /= 1;
        com.index = index;
        return {
            x: com.x,
            y: com.y
        }
    });

    let lockModels = [];
    let addNum = 0;
    while (unLockModels.length != 0 && addNum < 20000) {
        await addModelSize(components,unLockModels);
        for (let i = 0, l = unLockModels.length; i < l; i++) {
            var model = unLockModels[i];
            if(model.widthLock && model.heightLock){
                lockModels.push(unLockModels.splice(i--, 1)[0]);
                console.log(model.list[0].layer + "进度1：" + lockModels.length + "/" + maxLength);
                l--;
                addNum = 0;
                continue;
            }
            addNum++;
        }
    }
    console.log("耗时：" + this.self.performance.now() / 1000 + "s");
    this.self.postMessage([...lockModels, ...unLockModels]);
});

// 增加一个型号的大小和高度
function addModelSize(components,unLockModels){

    let wFinish = unLockModels.every(model=>model.widthLock), hFinish = unLockModels.every(model=>model.heightLock);
    let addSize = 0.1;

    return new Promise((resolve,reject)=>{


        if (!wFinish) {
            unLockModels.forEach(model=>{
                if(!model.widthLock){
                    model.list.forEach(com => {
                        com.w = (com.w * 10 + addSize * 10) / 10;
                    });
                }
            })
            // 判断是否有碰撞
            groupCheck(unLockModels.filter(model=>!model.widthLock),components).then(detectorModels=>{
                wFinish = true;
                unLockModels.forEach(model=>{
                    if(!model.widthLock){
                        if(detectorModels.indexOf(model.model) !== -1){
                            model.widthLock = true;
                        }else{
                            model.list.forEach(com => {
                                com.w = (com.w * 10 + addSize * 10) / 10;
                            });
                        }
                    }
                });
                    
                if(wFinish && hFinish){
                    resolve(true);
                }
            });

            unLockModels.forEach(model=>{
                if(!model.widthLock){
                    model.list.forEach(com => {
                        com.w = (com.w * 10 - addSize * 10) / 10;
                    });
                }
            })
        }
    
        // 增加高度
        if (!hFinish) {
            unLockModels.forEach(model=>{
                if(!model.heightLock){
                    model.list.forEach(com => {
                        com.h = (com.h * 10 + addSize * 10) / 10;
                    });
                }
            })
            // if(model.model == "TSOP56_20D2X14D2"){
            //     console.log("高度增加");
            // }
            // 判断是否有碰撞
            groupCheck(unLockModels.filter(model=>!model.heightLock),components).then(detectorModels=>{
                hFinish = true;
                unLockModels.forEach(model=>{
                    if(!model.heightLock){
                        if(detectorModels.indexOf(model.model) !== -1){
                            model.heightLock = true;
                        }else{
                            model.list.forEach(com => {
                                com.h += addSize;
                            });
                        }
                    }
                });
                if(wFinish && hFinish){
                    resolve(true);
                }
            });

            unLockModels.forEach(model=>{
                if(!model.heightLock){
                    model.list.forEach(com => {
                        com.h = (com.h * 10 - addSize * 10) / 10;
                    });
                }
            });
            
        }

        
        if(wFinish && hFinish){
            resolve(true);
        }
    })
}

let workers = [];
// 线程池
function getWorker(){
    if(workers.length){
        return workers.pop();
    }
    else{
        var blob = new Blob(['importScripts("http://192.168.80.22:5501/compareWorker.js")'], {"type": 'application/javascript'});
    
        var blobUrl = URL.createObjectURL(blob);
    
        let worker = new Worker(blobUrl);
        return worker;
    }
}

// 归还worker
function giveWorker(worker){
    worker.onmessage = null;
    workers.push(worker);
}

// 销毁线程
function cancelWorker(){
    workers.forEach(worker=>{
        worker.terminate();
    })
}

// 分组检测碰撞
function groupCheck(unLockModels,components){
    // console.log(components)
    // 将需要检测的型号进行分组

    
    let checkGroup = [];

    let i = 0,size = 0;
    
    let checkComponents = unLockModels.map(model => model.list).flat();

    checkComponents.forEach(com=>{
        i++;
        if(i == 1){
            size++;
            checkGroup.push([]);
        }
        checkGroup[size - 1].push(com);
        if(i == 200){
            i = 0;
        }
    });
    // console.log(checkGroup)
    let comGroup = [];

    i = 0,size = 0;

    components.forEach(com=>{
        i++;
        if(i == 1){
            size++;
            comGroup.push([]);
        }
        comGroup[size - 1].push(com);
        if(i == 500){
            i = 0;
        }
    });

    // i = 0;
    return new Promise((resolve,reject)=>{
        let detectorModels = [];
        let count = checkGroup.length * comGroup.length;
        let sum = 0;
        checkGroup.forEach(checkComs=>{
            // console.log("线程数量",++i)
            comGroup.forEach(coms=>{
                let worker = getWorker();
    
                worker.postMessage({check:checkComs,components:coms});
    
                worker.onmessage = (e)=>{
                    sum++;
                    detectorModels.push(...e.data);
                    if(sum == count){
                        resolve([...new Set(detectorModels)]);
                    }
                    giveWorker(worker);
                };
            });
        });
    });
}
